package com.xunchi.haichuan.user.dao;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;

import com.netai.safedoc.common.dao.BaseEntityDAOImpl;
import com.xunchi.haichuan.user.model.User;
import com.xunchi.haichuan.utility.Constants;

/**
 * 作者：kongxb<br>
 * 模块名称：用户模块<br>
 * 功能描述：用户数据存取实现<br>
 * 维护记录：
 */
public class UserDAOImpl extends BaseEntityDAOImpl<User> implements UserDAO {

	/**
	 * 默认构造方法
	 */
	public UserDAOImpl() {
		super();
	}

	/**
	 * 构造方法
	 * 
	 * @param user
	 */
	public UserDAOImpl(Class<User> user) {
		super(user);
	}

	/**
	 * @see com.xunchi.haichuan.user.dao.UserDAO#getUser(java.lang.String, java.lang.String)
	 */
	public User getUser(String loginName, String loginPassword) throws Exception {
		User user = null;
		DetachedCriteria dc = DetachedCriteria.forClass(User.class);
		dc.add(Restrictions.eq("loginName", loginName));
		dc.add(Restrictions.eq("loginPassword", loginPassword));
		List<User> list = this.findByDetachedCriteria(dc);

		if (!list.isEmpty()) {
			user = (User) list.get(0);
		}
		return user;
	}

	/**
	 * @see com.xunchi.haichuan.user.dao.UserDAO#getUser(java.lang.String, java.lang.String, int)
	 */
	public User getUser(String loginName, String loginPassword, int type) throws Exception {
		User user = null;
		DetachedCriteria dc = DetachedCriteria.forClass(User.class);
		dc.add(Restrictions.eq("loginName", loginName));
		dc.add(Restrictions.eq("loginPassword", loginPassword));
		dc.add(Restrictions.eq("type", type));
		List<User> list = this.findByDetachedCriteria(dc);

		if (!list.isEmpty()) {
			user = (User) list.get(0);
		}
		return user;
	}

	/**
	 * @see com.xunchi.haichuan.user.dao.UserDAO#checkLoginName(java.lang.String)
	 */
	public boolean checkLoginName(String loginName) throws Exception {
		String hql = "from User where loginName = ?";
		List<User> list = findByHql(hql, loginName);
		return !list.isEmpty();
	}

	/**
	 * @see com.xunchi.haichuan.user.dao.UserDAO#getByParentId(java.lang.String)
	 */
	public List<User> getByParentId(String parentId) throws Exception {
		if (parentId == null) {
			String hql = "from User where status = 1 and parentId is null";
			return findByHql(hql);
		} else {
			String hql = "from User where status = 1 and parentId = ?";
			return findByHql(hql, parentId);
		}
	}

	/**
	 * @see com.xunchi.haichuan.user.dao.UserDAO#getByType(java.lang.Integer)
	 */
	public List<User> getByType(int type) throws Exception {
		String hql = "from User where status = 1 and type = ?";
		return findByHql(hql, type);
	}

	/**
	 * @see com.xunchi.haichuan.user.dao.UserDAO#changeStatus(java.lang.String, java.lang.Integer)
	 */
	public void changeStatus(String usrId, int status) throws Exception {
		String hql = "User set status = " + status + " where usrId = '" + usrId + "'";
		this.updateByHql(hql);
	}

	/**
	 * @see com.xunchi.haichuan.user.dao.UserDAO#changePwd(java.lang.String, java.lang.String, java.lang.String)
	 */
	public int changePwd(String usrId, String password, String oldPassword) throws Exception {
		StringBuffer hql = new StringBuffer();
		hql.append("update User as model set model.loginPassword = '" + password + "' where model.usrId = '" + usrId
				+ "'");
		if (StringUtils.isNotEmpty(oldPassword)) {
			hql.append(" and model.loginPassword = '" + oldPassword + "'");
		}
		int result = this.getSession().createQuery(hql.toString()).executeUpdate();
		return result;
	}

	/**
	 * @see com.xunchi.haichuan.user.dao.UserDAO#changeBalance(java.lang.String, java.lang.Float)
	 */
	public void changeBalance(String usrId, float balance) throws Exception {
		String hql = "User set balance = " + balance + " where usrId = '" + usrId + "'";
		this.updateByHql(hql);
	}

	/**
	 * @see com.xunchi.haichuan.user.dao.UserDAO#search(com.xunchi.haichuan.user.model.User, java.util.Date,
	 *      java.util.Date)
	 */
	public List<User> search(User instance, Date beginDate, Date endDate) {
		log.debug("searching User instance");
		try {
			DetachedCriteria dc = getEntityDetachedCriteria();
			if (StringUtils.isNotEmpty(instance.getName())) {
				dc.add(Restrictions.like("name", instance.getName(), MatchMode.ANYWHERE));
			}
			if (StringUtils.isNotEmpty(instance.getLoginName())) {
				dc.add(Restrictions.ilike("loginName", instance.getLoginName(), MatchMode.ANYWHERE));
			}
			// 日期匹配从 beginDate 00:00:00 开始到 endDate 23:59:59，即 >= beginDate 00:00:00 and < endDate+1 00:00:00
			if (beginDate != null) {
				dc.add(Restrictions.ge("submitTime", beginDate));
			}
			if (endDate != null) {
				endDate = DateUtils.addDays(endDate, 1);
				dc.add(Restrictions.lt("submitTime", endDate));
			}
			if (Constants.DB_NONE != instance.getStatus()) {
				dc.add(Restrictions.eq("status", new Integer(instance.getStatus())));
			}
			if (StringUtils.isNotEmpty(instance.getParentId())) {
				dc.add(Restrictions.eq("parentId", instance.getParentId()));
			}
			if (Constants.DB_NONE != instance.getType()) {
				dc.add(Restrictions.eq("type", new Integer(instance.getType())));
			}

			return findByDetachedCriteria(dc);
		} catch (RuntimeException re) {
			log.error("search User instance failed", re);
			throw re;
		}
	}

	/**
	 * @see com.xunchi.haichuan.user.dao.UserDAO#search(com.xunchi.haichuan.user.model.User, java.util.Date,
	 *      java.util.Date, int, int)
	 */
	public List<User> search(User instance, Date beginDate, Date endDate, int start, int limit) {
		log.debug("searching User instance");
		try {
			DetachedCriteria dc = getEntityDetachedCriteria();
			if (StringUtils.isNotEmpty(instance.getName())) {
				dc.add(Restrictions.like("name", instance.getName(), MatchMode.ANYWHERE));
			}
			if (StringUtils.isNotEmpty(instance.getLoginName())) {
				dc.add(Restrictions.ilike("loginName", instance.getLoginName(), MatchMode.ANYWHERE));
			}
			// 日期匹配从 beginDate 00:00:00 开始到 endDate 23:59:59，即 >= beginDate 00:00:00 and < endDate+1 00:00:00
			if (beginDate != null) {
				dc.add(Restrictions.ge("submitTime", beginDate));
			}
			if (endDate != null) {
				endDate = DateUtils.addDays(endDate, 1);
				dc.add(Restrictions.lt("submitTime", endDate));
			}
			if (Constants.DB_NONE != instance.getStatus()) {
				dc.add(Restrictions.eq("status", new Integer(instance.getStatus())));
			}
			if (StringUtils.isNotEmpty(instance.getParentId())) {
				dc.add(Restrictions.eq("parentId", instance.getParentId()));
			}
			if (Constants.DB_NONE != instance.getType()) {
				dc.add(Restrictions.eq("type", new Integer(instance.getType())));
			}

			Criteria criteria = dc.getExecutableCriteria(getSession());
			return criteria.setFirstResult(start).setMaxResults(limit).list();
		} catch (RuntimeException re) {
			log.error("search User instance failed", re);
			throw re;
		}
	}

	@SuppressWarnings("unchecked")
	public List<User> findByProperty(String propertyName, Object value) {
		log.debug("finding User instance with property: " + propertyName + ", value: " + value);
		try {
			String queryString = "from User as model where model." + propertyName + "= ?";
			return getHibernateTemplate().find(queryString, value);
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	public List<User> findByLoginName(Object loginName) {
		String LOGIN_NAME = "loginName";
		return findByProperty(LOGIN_NAME, loginName);
	}
}
